#include "vigenere.h"

vigenere::vigenere()
{
	current_key_index = 0;
}

bool vigenere::load_keys_from_file(string fileDir)
{
	ifstream file;
	file.open(fileDir);
	if (file.good())
	{
		while (!file.eof())
		{
			string key;
			getline(file, key);
            keys.push_back(delete_special_char_from_key(key));
		}
        file.close();
		return true;
	}
	else return false;
}

int vigenere::keys_count()
{
	return keys.size();
}

string vigenere::delete_special_char_from_key(string key)
{
	string result = "";
	for (int i = 0; i < key.length(); i++)
	{
		if ((key[i] >= 97 && key[i] <= 122) || (key[i] >= 65 && key[i] <= 90)) result += key[i];
	}
	return result;
}

string vigenere::encrypt(string plainText)
{
    string unique_key = keys[current_key_index++];
    string cryptogram = "";
    for (int i = 0, j = 0; i < plainText.length(); i++)
	{
        if (plainText[i] >= 97 && plainText[i] <= 122)
		{
            unique_key[j] = tolower(unique_key[j]);
            cryptogram += ((plainText[i] + unique_key[j] - 194) % 26) + 97;
			j++;
		}
        else if (plainText[i] >= 65 && plainText[i] <= 90)
		{
            unique_key[j] = toupper(unique_key[j]);
            cryptogram += ((plainText[i] + unique_key[j] - 130) % 26) + 65;
			j++;
		}
		else
		{
            cryptogram += plainText[i];
		}
	}
    return cryptogram;
}

string vigenere::decrypt(string cryptogram)
{
    string unique_key = keys[current_key_index++];
    string decrypted = "";
    for (int i = 0, j = 0; i < cryptogram.length(); i++)
    {
        if (cryptogram[i] >= 97 && cryptogram[i] <= 122)
        {
            unique_key[j] = tolower(unique_key[j]);
            if (cryptogram[i] - unique_key[j] < 0)
                decrypted += cryptogram[i] - unique_key[j] + 26 + 97;
            else
                decrypted += cryptogram[i] - unique_key[j] + 97;
            j++;
        }
        else if (cryptogram[i] >= 65 && cryptogram[i] <= 90)
        {
            unique_key[j] = toupper(unique_key[j]);
            if (cryptogram[i] - unique_key[j] < 0)
                decrypted += cryptogram[i] - unique_key[j] + 26 + 65;
            else
                decrypted += cryptogram[i] - unique_key[j] + 65;
            j++;
        }
        else
        {
            decrypted += cryptogram[i];
        }
    }
    return decrypted;
}

int vigenere::current_key_length()
{
    if (keys.empty())
        return 0;
    else
        return keys[current_key_index].length();
}
